<template>
	<div class="editor-wrap">
		
		<!-- 富文本编辑 -->
		<quill-editor 
        v-model="content" 
        ref="myQuillEditor" 
        :options="editorOption" 
        @blur="onEditorBlur($event)" 
        @focus="onEditorFocus($event)"
        @change="onEditorChange($event)">
    </quill-editor>

        <!-- 图片添加 -->
    	<upload-dialog
      		:visible.sync="uploadDialogVisible"
      		@close="uploadDialogClose"
      		@confirm="insertImgToContent"
    	></upload-dialog>

	</div>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import Quill from 'quill'

/*创建自定义图片*/
const Embed = Quill.import('blots/block/embed');

class IpcImage extends Embed{
  static create(value){
    let node = super.create();
    IpcImage.buildDiv(value,node)
    return node
  }

  static value(node) {
    return node.dataset.src;
  }

  static buildDiv(value,node){
    node.setAttribute('data-name', 'ipc-image');
    node.setAttribute('data-src', value);
    Object.assign(node.style,{
      textAlign:'center',
      lineHeight:'0',
      margin:'20px 0'
    });
    let image = document.createElement('img');
    image.setAttribute('width',440);
    image.setAttribute('src',value);

    node.appendChild(image)

  }
}


IpcImage.blotName = 'ipcImage';
IpcImage.className = 'ql-ipace-image';
IpcImage.tagName = 'div';

Quill.register(IpcImage)

//定义富文本工具栏标题
const titleConfig = {
    "ql-bold": "加粗" ,
  	"ql-color": "颜色",
  	"ql-font": "字体",
  	"ql-code": "插入代码",
  	"ql-italic": "斜体",
  	"ql-link": "添加链接",
  	"ql-background": "背景颜色",
  	"ql-size": "字体大小",
  	"ql-strike": "删除线",
  	"ql-script": "上标/下标",
  	"ql-underline": "下划线",
  	"ql-blockquote": "引用",
  	"ql-header": "标题",
  	"ql-indent": "缩进",
  	"ql-list": "列表",
  	"ql-align": "文本对齐",
  	"ql-direction": "文本方向",
  	"ql-code-block": "代码块",
  	"ql-formula": "公式",
  	"ql-image": "图片",
  	"ql-video": "视频",
  	"ql-clean": "清除字体样式",
  	"ql-upload": "文件",
  	"ql-customImage": "上传图片",
    "ql-hot": "热点",
    "ql-ecnet": "纠错",
    "ql-summary": "摘要",
    "ql-topic": "分类",
    "ql-keyword": "标签",
};


import UploadDialog from '../uploadDialog';

import website from '@/config/website'

const imgPreviewPrefix = website.imgPreviewPrefix;

export default{
	components: {
      	quillEditor,
      	UploadDialog,
    },
	props:{
		value:{
			type:String,
			default:''
		}
	},
	watch:{
		//监听value的变化，更新本地数据
		value(newVal){
      console.log(newVal, '000000000')
			this.content = newVal;
		},
		//监听本地数据变化，使用input事件通知父组件更新
		content(newVal){
			this.$emit('input',newVal);
		}
	},
	data(){
		var _this = this;

		return{
      
			uploadDialogVisible:false,
			content:this.value,
			editorOption: {
              	placeholder: '请输入正文',
              	modules:{
                	toolbar:{
                  		container:[
                    		['bold','italic','underline','strike'],
                    		['blockquote','code-block'],
                    		[{'header':1},{'header':2}],
                    		[{'list':'ordered'},{'list':'bullet'}],
                    		[{'script':'sub'},{'script':'super'}],
                    		[{'indent':'-1'},{'indent':'+1'}],
                    		[{'direction':'rtl'}],
                    		[{'size':['small',false,'large','huge']}],
                    		[{'header':[1,2,3,4,5,6,false]}],
                    		[{'color':[]},{'background':[]}],
                    		[{'font':[]}],
                    		[{'align':[]}],
                    		['clean'],
                    		['customImage'],
                        ['hot'],
                        ['ecnet'],
                        ['summary'],
                        ['topic'],
                        ['keyword'],
                  		],
                  		handlers:{
                    		shadeBox:null,
                    		customImage:function(){
                      			_this.uploadDialogVisible = true
                    		},
                        hot:function(){
                            _this.$emit('assist-api',{name:'hot',type:1})
                        },
                        ecnet:function(){
                            _this.$emit('assist-api',{name:'ecnet',type:2})
                        },
                        summary:function(){
                            _this.$emit('assist-api',{name:'summary',type:3})
                        },
                        topic:function(){
                           _this.$emit('assist-api',{name:'topic',type:3})
                        },
                        keyword:function(){
                           _this.$emit('assist-api',{name:'keyword',type:3}) 
                        }
                  		}

                	}

              	}

            },

        
		}
	},
	mounted(){
		this.addQuillTitle();
		this.initButton();
	},
	computed: {
        editor() {
            return this.$refs.myQuillEditor.quill;
        },
    },
	methods:{
    
		// 失去焦点事件
		onEditorBlur(ev){

		}, 
		// 获得焦点事件
        onEditorFocus(ev){

        },
        // 内容改变事件 
        onEditorChange(ev){

        }, 
        //添加富文本标题提示
        addQuillTitle(){
          	const oToolBar = document.querySelector(".ql-toolbar"),
                aButton = oToolBar.querySelectorAll("button"),
                aSelect = oToolBar.querySelectorAll("select");

            aButton.forEach(function(item){
              	if(item.className === "ql-script"){
                	item.value === "sub" ? (item.title="下标") : (item.title="上标")
              	}else if(item.className === "ql-indent"){
                	item.value === "+1" ? (item.title="向右缩进") : (item.title="向左缩进")
              	}else{
                	item.title = titleConfig[item.classList[0]];
              	}
            });

            aSelect.forEach(function(item){
              	item.parentNode.title = titleConfig[item.classList[0]];
            });
        },
        //初始化自定义按钮
        initButton(){
          	//图片上传添加按钮
          	const customImage = document.querySelector('.ql-customImage');
          	customImage.innerHTML="<i class=\"icon iconfont ipc-add-image\"></i>";

            //热点
            const hot = document.querySelector('.ql-hot');
            hot.style.cssText="width:50px;background:#eaeaea;border-radius:5px;font-size:12px;margin-top:5px;height:20px;";
            hot.innerText="热点";
            //纠错
            const ecnet = document.querySelector('.ql-ecnet');
            ecnet.style.cssText="width:50px;background:#eaeaea;border-radius:5px;font-size:12px;margin-top:5px;height:20px;";
            ecnet.innerText="纠错";
            //摘要
            const summary = document.querySelector('.ql-summary');
            summary.style.cssText="width:50px;background:#eaeaea;border-radius:5px;font-size:12px;margin-top:5px;height:20px;";
            summary.innerText="摘要";
            //分类
            const topic = document.querySelector('.ql-topic');
            topic.style.cssText="width:50px;background:#eaeaea;border-radius:5px;font-size:12px;margin-top:5px;height:20px;";
            topic.innerText="分类";
            //标签
            const keyword = document.querySelector('.ql-keyword');
            keyword.style.cssText="width:50px;background:#eaeaea;border-radius:5px;font-size:12px;margin-top:5px;height:20px;";
            keyword.innerText="标签";
        },
        //选择图片模态框关闭
        uploadDialogClose(){
          	this.uploadDialogVisible = false;
        },
        //上传图片成功后点击确定插入图片到富文本
        insertImgToContent(imgs){
          	let quill = this.$refs.myQuillEditor.quill;
          	for(var i=0;i<imgs.length;i++){
            	/*imgs[i]['selected'] = false;
            	if(imgs[i]['selectIndex']){
              		delete imgs[i]['selectIndex']
            	}*/

            	let length = quill.selection.savedRange.index;
            	quill.insertEmbed(length !== null ? length : 0,'ipcImage',imgPreviewPrefix+imgs[i],Quill.sources.USER)
          	}

          	//将插入的图片推入缓存去
          	//this.cacheImgs = this.cacheImgs.concat(imgs);
          	this.$emit('updateCacheImg',imgs);

          	console.log("%c插入到正文的图片","background:#90c;color:#fff")
          	console.log(imgs)

          	//关闭模态框
          	this.uploadDialogVisible = false;
        },
	}

}	

</script>


<style>
  /*设置富文本高度*/
  .ql-editor{
    height:350px;
    line-height: 2;
  }

  .ql-editor.ql-blank::before {
    font-style: normal;
    font-size: 16px;
    line-height: 25px;
    color: #999;
    
  }

  .ql-editor h1{
    color: #222!important;
    position: relative;
    padding-left: 15px;
  }

  .ql-editor h1:before{
    position: absolute;
    content: "";
    top: 12px;
    left: 0;
    width: 4px;
    height: 28px;
    background: #de504a;
  }

  .ql-snow .ql-editor img {
    max-width: 440px;
  }
</style>



